package com.chebaohui.iqs.service.impl.deal.libao.sdk;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.chebaohui.iqs.service.impl.deal.libao.util.LibaoConfig;

public class SignUtil {
	public static String buildSign(Map<String, String> sParaTemp) {
		Map<String, String> sPara = paramFilter(sParaTemp);

		String prestr = createLinkString(sPara);
		String mysign = MD5.sign(prestr, LibaoConfig.pdk, "utf-8");

		return mysign;
	}

	public static boolean verifySign(Map<String, String> sParaTemp, String sign) {
		String text = buildSign(sParaTemp);

		return MD5.verify(text, sign, LibaoConfig.pdk, "utf-8");
	}

	@SuppressWarnings("rawtypes")
	public static Map<String, String> paramFilter(Map<String, String> sArray) {
		Map<String, String> result = new HashMap<String, String>();

		if ((sArray == null) || (sArray.size() <= 0)) {
			return result;
		}

		Set<?> ent = sArray.entrySet();
		Map.Entry et = null;
		for (Iterator it = ent.iterator(); it.hasNext();) {
			et = (Map.Entry) it.next();

			if ((et.getValue() != null) && (!((String) et.getValue()).equals(""))
					&& (!((String) et.getKey()).equalsIgnoreCase("sign"))
					&& (!((String) et.getKey()).equalsIgnoreCase("pdk"))) {
				result.put(et.getKey().toString(), et.getValue().toString());
			}
		}
		return result;
	}

	private static String createLinkString(Map<String, String> params) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);

		StringBuilder prestr = new StringBuilder("?");
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			String value = (String) params.get(key);

			if (i > 0) {
				prestr.append("&");
			}
			prestr.append(key).append("=").append(value);
		}

		return prestr.toString();
	}
}
